/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package medialibrary.servlet;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;
import medialibrary.persistence.Administrator;
import medialibrary.persistence.Membre;

/**
 *
 * @author user
 */
@WebServlet(name="AuthenticateServlet", urlPatterns={"/Authenticate"})
public class AuthenticateServlet extends HttpServlet {
    
    @PersistenceUnit
    //The emf corresponding to 
    private EntityManagerFactory emf;  
    
    @Resource
    private UserTransaction utx;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {
        assert emf != null;  //Make sure injection went through correctly.
        EntityManager em = null;
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=UTF-8");
        try {
            try{    
            if(session.getAttribute("usertype")=="user"){
              response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/MemberUIServlet") );
            }else if(session.getAttribute("usertype")=="admin"){
                response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/AdminUI.jsp") );
            }
            }catch(Exception e){}
            //Get the data from the authentication form
            String login    = (String) request.getParameter("login");
            String password = (String) request.getParameter("password");
            
            //begin a transaction
            utx.begin();
            //create an em. 
            //Since the em is created inside a transaction, it is associsated with the transaction
            em = emf.createEntityManager();
            

            Query queryMember = em.createQuery("select m from Membre m where m.login = :login and m.password = :password");
            Query queryAdmin = em.createQuery("select m from Administrator m where m.login = :login and m.password = :password");
            queryMember.setParameter("login", login);
            queryMember.setParameter("password", password);
            queryAdmin.setParameter("login", login);
            queryAdmin.setParameter("password", password);
            
            try {
                Membre m=(Membre) queryMember.getSingleResult();
                session.setAttribute("id", m.getMemberId());
                session.setAttribute("usertype", "user");
                response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/MemberUIServlet") );
            }   catch(NoResultException e1) {
                try { 
                    Administrator a=(Administrator) queryAdmin.getSingleResult();
                    session.setAttribute("id", a.getAdministratorId());
                    session.setAttribute("usertype", "admin");
                    response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/AdminUI.jsp") );
                }   catch(NoResultException e2) {
                        response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/index.jsp") );
                    }
                }
        
            utx.commit();
            
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {            
            if(em != null) {
                em.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
